package controllers.api;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import play.mvc.Router;
import play.mvc.Http.StatusCode;
import models.InboxMessage;
import models.Message;
import models.User;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import controllers.Data;

public class Inbox extends MeApi {
	
	public static void list(Integer offset, Integer limit) {
		if(offset == null) offset = 0;
		if(limit==null || limit > LIMIT || limit==0) {
			limit = LIMIT;
		}
		User current = getCurrentUser();
		Data<InboxMessage> data = new Data<InboxMessage>();
		List<InboxMessage> messages = InboxMessage.paginate(InboxMessage.findReceived(current), offset, limit);
		data.total = InboxMessage.countReceived(current);
		data.data = messages;
		renderTemplate("api/messageList.json",data);
	}
	
	public static void get(Long id) {
		User current = getCurrentUser();
		InboxMessage message = InboxMessage.getReceived(id, current);
		if(message==null) notFound();
		//if(message.owner.id.longValue() != current.id.longValue()) forbidden();
		if(!message.readed) {
			message.readed = Boolean.TRUE;
			message.update();
		}
		renderTemplate("api/message.json",message);
	}
	
	public static void delete(Long id) {
		User current = getCurrentUser();
		InboxMessage message = InboxMessage.getReceived(id, current);
		if(message==null) notFound();
		//if(message.owner.id.longValue() != current.id.longValue()) forbidden();
		message.delete();
	}
	
	public static void edit(Long id, JsonObject body) {
		User current = getCurrentUser();
		InboxMessage message = InboxMessage.getReceived(id, current);
		//Message msgJSON = gson().fromJson(body, Message.class);
		if(message==null) notFound();
		//if(message.id != msgJSON.id) notFound();
		//if(message.to.id.longValue() != current.id.longValue()) forbidden();
		// Copy updateable properties from the JSON object to the original.
		message.readed = body.get("readed").getAsBoolean();
		message.update();
		response.status = StatusCode.OK;
		Map map = new HashMap();
		map.put("id", message.id);
		String url = Router.reverse("api.Subscribers.get", map).url;// GET /clients/1541
		response.setHeader("location", url);
	}
	
}